﻿/// <reference path="JSintellisense/jquery-1.3.2-vsdoc2.js" />

var isselfdispatch = $("#hfisselfdispatch");


///提交订单
function checkorder() {

    var flag = j_submitdata("publishorderdata");

    if (!flag) {
        return false;
    }

    var tbtel = $("#OrderComm").val();
    var myreg = /^\d*$/;
    if (!myreg.test(tbtel)) {
        alert("手机(电话)号码格式错误.")
        return false;
    }

    var tbaddressdetail = $("#tbaddressdetail").val();
    var hidhasaddr = $("#hidhasaddr").val();
    if (hidhasaddr == "0" && tbaddressdetail == "") {
        alert("请输入您的详细地址.")
        return false;
    }
    $(".mModal").show();
    $("#loadingbox").show();

    return true;
}

var tipbox = $("#tipbox");
var hftip = $("#hftip");


$(function () {
    $(".x,.mModal").click(function () {
        $(".mModal,.mDialog").hide();
    });


    $(".additem").bind("touchend", function (event) {
        var count = parseInt(tipbox.html());
        tipbox.html((count + 1) + "");
        hftip.val((count + 1) + "");

    });


    //减分数
    $(".subitem").bind("touchend", function (event) {
        var count = parseInt(tipbox.html());
        if (count <= 1) {
            count = 0;
        }
        else {
            count = parseInt(count) - 1;
        }

        tipbox.html(count + "");
        hftip.val((count) + "");
    })

    initialize();


    var options = {
        success: function (data) {
            $(".mModal").hide();
            $("#loadingbox").hide();


            var json = eval("(" + data + ")");

            if (json.state == "1") {

                var issalef = isselfdispatch.val();
                if (issalef == "1") {
                    window.location = "selfdispatchh5.aspx?id=" + json.data.id + "&lat=" + json.data.lat + "&lng=" + json.data.lng + "";
                    return;
                }

                swal({
                    title: "温馨提示",
                    text: "订单提交成功",
                    type: "success"
                },
                        function () {
                            window.location = "publishorder.aspx";
                        });
            }
            else {
                swal({
                    title: "温馨提示",
                    text: "系统错误，请联系管理员",
                    type: "error"
                });
            }
        }
    };

    // ajaxSubmit
    $("#btsubmit").click(function () {
        if (checkorder()) {
            isselfdispatch.val("0");
            $("#addform").ajaxSubmit(options);
        }
    });


    // ajaxSubmit
    $("#btSaveself").click(function () {
        if (checkorder()) {
            isselfdispatch.val("1");
            $("#addform").ajaxSubmit(options);
        }
    });

})

var mypoint = null;
var myGeo = null;
var hfcityname = $("#hfcityname").val();
var myValue = "";
function initialize() {
    myGeo = new BMap.Geocoder();

    //建立一个自动完成的对象
    var ac = new BMap.Autocomplete({ "input": "keyaddress", "location": hfcityname });
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件

        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;

        setPlace();


    });

}



function setPlace() {
    var address = $("#keyaddress").val();
    var cityname = hfcityname;

    var patrn = /\d+号/; //有具体的门牌号是要用地址解析，否则使用智能搜索
    if (patrn.test(address)) {
        myGeo.getPoint(address, function (point) {
            if (point) {
                mypoint = point;
                setLatLng(point);

                searchSuccess();
            }
            else {
                searchFail();
            }
        }, cityname);

    }
    else {

        var local = new BMap.LocalSearch(cityname, {
            autoViewport: true,
            selectFirstResult: true,
            onSearchComplete: function (result) {
                if (result != null && result.getPoi(0) != null) {
                    mypoint = result.getPoi(0).point;
                    setLatLng(mypoint);
                    searchSuccess();
                }
                else {
                    searchFail();
                }
            }

        });


        local.search(address);
    }
}


function searchSuccess() {
    setaddress(mypoint.lat, mypoint.lng, myValue, 0);
}

function searchFail() {
    alert("定位失败，请重新选择地址");
}




function setLatLng(point) {
    document.getElementById("hidlat").value = point.lat;
    document.getElementById("hidlng").value = point.lng;

    return true;
}


///配送费规则
function showlaw() {
    $(".mModal").show();
    $("#sendfeelaw").show();

    var clientHeight = document.documentElement.clientHeight;
    $("#sendfeelaw").css({ "margin-top": (-clientHeight * 0.4) + "px" });
}


///备注快捷选择
function showremarkbox() {
    $(".mModal").show();
    $("#remarktip").show();

    var clientHeight = document.documentElement.clientHeight;
    $("#remarktip").css({ "margin-top": (-clientHeight * 0.4) + "px" });
}

function settag(tag) {
    var or = $("#tbremark").val();
    $("#tbremark").val(or + " " + $(tag).attr("mytag"));
    $(tag).addClass("cull");
}

function completeremark() {
    var or = $("#tbremark").val();
    $("#OrderAttach").val(or);
    if (or.length == 0) {
        or = "选填";
    }
    $("#remarkbox").html(or);
    $(".mModal,.mDialog").hide();
}

//输入完成后，到下一个输入框
function telcheck() {
    var tel = document.getElementById("OrderComm").value + "";
    if (tel.length >= 11) {
        getaddressByTel();
        $("#tbPrice").focus();
    }
}


///根据电话获取地址
function getaddressByTel() {
    $("#hidtlat").val("");
    $("#hidtlng").val("");
    $("#tbaddress").val("");
    $("#hidhasaddr").val("0");


    var OrderComm = $("#OrderComm").val();
    jQuery.ajax(
    {
        type: "get",
        url: "/ajaxHandler.ashx",
        data: 'method=getaddressByTel&tel=' + OrderComm + "&t=" + new Date().getTime(),
        success: function (msg) {
            //alert(msg);

            var addrjson = eval("(" + msg + ")");
            if (addrjson.length > 0) {

                setaddress(addrjson[0].Lat, addrjson[0].Lng, addrjson[0].Address, 1);
                $("#addressbox").html($("#addressTemplate").render(addrjson));

            }


        }
    });
}



function getsendfee(shopid, price, lat, lng) {
    jQuery.ajax(
    {
        type: "post",
        url: "/ajaxHandler.ashx",
        data: "method=getSendFee&shopid=" + shopid + "&lat=" + lat + "&lng=" + lng + "&price=" + price + "&time=" + new Date().getTime() + "",
        success: function (msg) {

            parsedata(msg);
        }
    })
}

function parsedata(msg) {
    var json = eval("(" + msg + ")");
    $("#tbcardpay").val(json.Distance);
    $("#tbshopdiscountmoney").val(json.sendmoney);
    $("#distancebox").show();
    $("#distancemsg").html("距发货地" + json.Distance + "KM");
    $("#lbsendfee").html(json.sendmoney + "");
}

///计算配送费
function culSenFee() {
    var tbPrice = $("#tbPrice").val();
    if (tbPrice == "") {
        alert("请输入总金额");;
        return;
    }
    getsendfee($("#hftid").val(), $("#tbPrice").val(), $("#hidlat").val(), $("#hidlng").val())
}

//地址搜索框
function showmap() {

    $("#maptipbox").show();
    $(".mModal").show();
    searchPlaceOnMap();
}

function searchPlaceOnMap() {

    var address = $("#keyaddress").val();

    if (address.length == 0) {
        //swal("", "请输入地址", "warning");
        return;
    }

    var cityname = $("#hfcityname").val();
    var local = new BMap.LocalSearch(cityname, {
        renderOptions: {
            map: map,
            autoViewport: true,
            selectFirstResult: false
        }
    });
    local.search(address);
}

function setaddress(lat, lng, address, hidhasaddr) {
    var _lat = parseFloat(lat);
    var _lng = parseFloat(lng);
    var point = new BMap.Point(_lng, _lat);

    setLatLng(point);

    $("#tbaddress").val(address);
    $("#keyaddress").val("");
    setLatLng(point);
    $("#hidhasaddr").val(hidhasaddr);
    $("#maptipbox").hide();
    $(".mModal").hide();
    culSenFee();

}